<template>
  <div class="common-container flex flex-col h-full">
    <main-title>
      <el-button type="primary" class="btn-add" size="small" @click="create">新用户</el-button>
    </main-title>
    <div class="content-wrap flex flex-1 flex-col h0">
      <div class="search-wrap">
        <div class="common-search ym-box">
          <el-form :model="queryForm" inline @submit.prevent>
            <el-form-item class="type-item">
              <el-select v-model="queryType" placeholder="请选择">
                <el-option
                  v-for="item in queryTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label class="search-input">
              <el-input
                v-model="queryForm.query"
                :placeholder="inputPlaceholder"
                @keyup.enter="search"
              >
                <template #append>
                  <el-button style="vertical-align: middle" @click="search">
                    <el-icon>
                      <Search />
                    </el-icon>
                  </el-button>
                </template>
              </el-input>

              <!-- <search-input
                v-model="queryForm.query"
                :placeholder="inputPlaceholder"
                @search="search"
              />-->
            </el-form-item>
            <!-- <el-form-item class="btn-search-item">
              <el-button type="primary" class="btn-search" @click="search">查询</el-button>
            </el-form-item>-->
          </el-form>
        </div>
        <refresh-btn @refresh="search" />
      </div>
      <div class="table-wrap ym-box">
        <ym-table
          v-loading="state.tableLoading"
          :data="state.tableData"
          :column-data="userColumnData"
        >
          <template #info="{ row }">
            <table-account-info :info="row" />
          </template>

          <template #status="{ row }">
            <span>{{ EnableEnum[row.enable] }}</span>
          </template>
          <template #operator="{ row }">
            <el-button link type="primary" class="font-size-18" @click="editInit(row)">
              <el-icon>
                <Edit />
              </el-icon>
            </el-button>
            <el-button link type="danger" class="font-size-18" @click="del(row)">
              <el-icon>
                <Delete />
              </el-icon>
            </el-button>
          </template>
        </ym-table>

        <pagination
          v-model:currentPage="state.pageObj.pageNum"
          v-model:pageSize="state.pageObj.pageSize"
          :total="state.pageObj.total"
          @pagination="search"
        />
      </div>
    </div>
  </div>

  <drawer
    v-model:visible="state.dialogVisible"
    :size="640"
    :title="state.dialogTitle"
    :save-loading="state.saveLoading"
    @cancel="handleClose"
    @confirm="confirm"
    @close="closeDrawer"
  >
    <add-or-edit-form
      ref="formWrapper"
      :is-add="state.isAdd"
      :role-data="roleData"
      :org-options="orgOptions"
      :save-loading="state.saveLoading"
      :sex-options="dictStore.dictData[dictIdMaps.sex]"
    />
  </drawer>
</template>

<script lang="ts" setup>
import { computed, nextTick, reactive, ref, toRefs } from 'vue'

import RefreshBtn from '@/components/CommonSearch/RefreshBtn/index.vue'
import TableAccountInfo from '@/components/UserInfo/TableAccountInfo.vue'
import AddOrEditForm from './AddOrEditForm.vue'

// import { codeMaps, getByDictCodeList } from '@/api/backend/dict'
import { getOrgList } from '@/api/backend/organization'
import RoleApi, { RoleType } from '@/api/backend/role'
import UserApi from '@/api/backend/user'
import { useDict } from '@/api/uses'

import { useDictStore } from '@/store/dict'

import { userColumnData } from '&/utils/columnData'

import { EnableEnum } from '@/configs/codeMaps'
import { commonHandle } from '@/views/mixins/common'
import { Drawer, MainTitle, Pagination, YmTable } from '&/mixins/useComponent'
import IBaseObj from '#/index'

const { state, handleAdd, handleEdit, handleClose, handleSearch, handleDelete, handleConfirm } =
  commonHandle()

const queryTypeOptions = [
  {
    label: '姓名',
    value: 'name',
    placeholder: '输入姓名进行查询',
  },
  {
    label: '登录账号',
    value: 'loginCode',
    placeholder: '输入登录账号进行查询',
  },
  {
    label: '手机号',
    value: 'phone',
    placeholder: '输入手机号进行查询',
  },
  {
    label: '邮箱',
    value: 'email',
    placeholder: '请输入邮箱进行查询',
  },
]

const _state: IBaseObj = reactive({
  queryForm: {
    query: '',
  },
  queryType: 'name',
  roleData: {},
  orgOptions: [],
})

const { queryForm, queryType, roleData, orgOptions } = toRefs(_state)

const inputPlaceholder = computed(() => {
  return queryTypeOptions.filter((val) => val.value === _state.queryType)[0].placeholder
})

const { dictIdMaps } = useDict()
const { getDictData } = useDictStore()
const dictStore = useDictStore()

const getRoleData = async () => {
  Promise.all([RoleApi.getRoleList(RoleType.role), RoleApi.getRoleList(RoleType.system)]).then(
    (result) => {
      _state.roleData.defRole = result[0] || []
      _state.roleData.sysRole = result[1] || []
    }
  )
}

const getOrgOptions = async () => {
  const ret = await getOrgList()
  _state.orgOptions = ret || []
}

const search = () => {
  handleSearch(UserApi.getUserByPage, {
    [_state.queryType]: _state.queryForm.query,
  })
}

const create = () => {
  handleAdd('创建用户')

  nextTick(() => {
    formWrapper.value.form.password = ''
  })
}

const editInit = async (row: IBaseObj) => {
  const ret = await UserApi.getUserById(row.uid)
  if (ret) {
    handleEdit('修改用户')
    nextTick(() => {
      Object.keys(formWrapper.value.form).forEach((key) => {
        formWrapper.value.form[key] = ret.userEntity[key]
      })
      const { roleDefId, roleId } = ret
      formWrapper.value.form.roleDefId = roleDefId
      formWrapper.value.form.roleId = roleId
      formWrapper.value.form.uid = ret.userEntity.uid
      formWrapper.value.form.oid = ret.oid
    })
  }
}

const del = (row: IBaseObj) => {
  handleDelete({
    url: UserApi.delUrl,
    id: row.uid,
    message: '此操作将永久删除该用户，是否继续?',
    success: search,
  })
}

const formWrapper = ref()
const addOrEditReset = () => {
  formWrapper.value.clear()
}

const closeDrawer = () => {
  state.isAdd = true
  addOrEditReset()
}

const confirm = async () => {
  const valid = await formWrapper.value.valid()
  const { roleId } = formWrapper.value.form
  const params = { ...formWrapper.value.form, roleId: roleId === '' ? null : roleId }
  if (!state.isAdd) {
    delete params.password
  }

  handleConfirm({
    valid,
    addApi: UserApi.saveUser,
    updateApi: UserApi.updateUser,
    params: params,
    cb: search,
  })
}

const init = () => {
  getDictData()
  getRoleData()
  getOrgOptions()
  search()
}

init()
</script>

<style lang="scss" scoped>
.search-wrap {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.type-item {
  :deep() {
    .el-form-item {
      &__content {
        width: 120px;
      }
    }
  }
}

.search-input {
  :deep() {
    .el-form-item {
      &__content {
        width: auto;
      }
    }

    .el-input__inner {
      width: 180px;
    }
  }
}

.group {
  &-list {
    display: flex;
    flex-direction: column;
  }

  &-item {
    display: flex;

    & > div {
      padding: 0 5px;
      border: 1px solid #000;
      border-radius: 4px;
    }

    & + & {
      margin-top: 5px;
    }
  }
}
</style>
@/api/backend/organization
